package com.example.chat.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chat.beans.Admin;
import com.example.chat.beans.Config;
import com.example.chat.beans.UserLike;
import com.example.chat.beans.Video;
import com.example.chat.config.StatusEnums;
import com.example.chat.mapper.AdminMapper;
import com.example.chat.mapper.UserLikeMapper;
import com.example.chat.mapper.VideoMapper;
import com.example.chat.result.*;
import com.example.chat.utils.CheckUtils;
import com.example.chat.utils.Global;
import com.example.chat.utils.OssUtil;
import freemarker.template.utility.StringUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class VideoService extends ServiceImpl<VideoMapper, Video> {
    @Resource
    CheckUtils checkUtils;
    @Resource
    AdminMapper adminMapper;
    @Resource
    UserLikeMapper userLikeMapper;
    @Resource
    Global global;
    @Resource
    OssUtil ossUtil;

    public ListResult<List<VideoResult>> listVideo(Integer userId, String token, int type, Integer page, Integer limit) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1401");
        if (apiResult.getStatus() != 1)
            return new ListResult<>(apiResult.getStatus(), apiResult.getMsg(), null, 0, 0, 0);
        ListResult<List<VideoResult>> result = new ListResult<>();
        int status = 0;
        String msg = "获取失败";
        try {
            if (type == 2)
                userId = 0;
            Page<Video> pages = new Page<>(page, limit);
            IPage<Video> iPages = baseMapper.selectBySearch(pages, type, userId);
            List<VideoResult> results = new ArrayList<>();
            for (Video video : iPages.getRecords()) {
                ossUtil.setAccessKeyId(global.getConfig().getAliyunId());
                ossUtil.setAccessKeySecret(global.getConfig().getAliyunKey());

                VideoResult videoResult = new VideoResult();
                videoResult.setId(video.getId());
                videoResult.setCreateAdmin(video.getCreateAdminName());
                videoResult.setCreateTime(Global.longToString(video.getCreateTime()));
                videoResult.setFilePath(ossUtil.getFileUrl(video.getFilePath(), 10000));
                videoResult.setCover(ossUtil.getVideoCover(video.getFilePath(), 10000));
                videoResult.setChatAdminName(video.getChatAdminName());
                videoResult.setType(video.getType());
                videoResult.setExpireTime(Global.longToString(video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L));
                if (video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L > System.currentTimeMillis())
                    videoResult.setIsExpire(2);
                else
                    videoResult.setIsExpire(1);
                videoResult.setName(video.getName());
                videoResult.setStatus(video.getStatus());
                videoResult.setStatusName(StatusEnums.getMessage(video.getStatus()));
                results.add(videoResult);
            }
            result.setData(results);
            result.setPage(page);
            result.setLimit(limit);
            result.setTotal(iPages.getTotal());
            msg = "获取成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> addVideo(Integer userId, String token, Integer chatAdminId, String filePath) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, filePath), userId, token, "1402");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "创建失败";
        try {
            Admin admin = adminMapper.selectById(chatAdminId);
            if (admin != null) {
                Config config = global.getConfig();
                if (config.getRecord() == 1) {
                    Video video = new Video();
                    video.setChatAdminId(chatAdminId);
                    video.setFilePath(filePath);
                    video.setCreateTime(System.currentTimeMillis());
                    video.setCreateAdmin(userId);
                    baseMapper.insert(video);
                    status = 1;
                    msg = "创建成功";
                } else msg = "录制开关未打开，不允许录制";
            } else msg = "录制对象用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> deleteVideo(Integer userId, String token, Integer[] ids) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "1404");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "删除失败";
        try {
            for (Integer id : ids) {
                Video video = baseMapper.selectById(id);
                if (video == null) {
                    continue;
                }
                baseMapper.deleteById(id);
                ossUtil.deleteFile("", video.getFilePath());
            }
            msg = "删除成功";
            status = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> publishVideo(Integer userId, String token, Integer videoId, String name, String cover, Integer videoType, int type) {

        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "");
        if (apiResult.getStatus() != 1){
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);}
        Video video = baseMapper.selectById(videoId);
        if (null != video) {
            if (ObjectUtils.isNotEmpty(video.getStatus()) && video.getStatus() > 10) {
                return new ApiResult<>(0, "视频不是待发布状态,不允许修改标题!", null);
            }
            ApiResult<Base> result = new ApiResult<>();
            int status = 1;
            String msg = "标题修改成功";
            video.setVideoType(videoType);
            video.setName(name);
            video.setCover(cover);
            if (type == 1) {
                video.setStatus(20);
                msg = "发布成功";
            }
            updateById(video);
            result.setStatus(status);
            result.setMsg(msg);
            return result;
        } else {
            return new ApiResult<>(0, "视频不存在!", null);
        }
    }

    public static long convertDateStringToTimestamp(String dateString) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
        // 将LocalDateTime转换为指定时区的Instant，然后获取其毫秒值
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

    }

    public ListResult<List<VideoResult>> listVideoBytype(String type, String name, Long videoType, String username, String startTime,
                                                         String endTime, Integer status, Integer isTop, Integer page, Integer limit) {

        ListResult<List<VideoResult>> result = new ListResult<>();
        Long start = null;
        Long end = null;
        if (StringUtils.isNotEmpty(startTime)) {
            start = convertDateStringToTimestamp(startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            end = convertDateStringToTimestamp(endTime);
        }
        int Resultstatus = 0;
        String msg = "获取失败";
        try {
            Page<Video> pages = new Page<>(page, limit);
            IPage<Video> iPages;
            if ("B".equals(type)) {
                iPages = baseMapper.selectVideoListForB(pages, name, videoType, username, start, end, status, isTop);
            } else if ("C".equals(type)){
                iPages = baseMapper.selectVideoListForC(pages, name, videoType, username, start, end, status, isTop);
            } else {
                result.setStatus(status);
                result.setMsg("参数类型错误");
                return result;
            }
            List<VideoResult> results = new ArrayList<>();
            for (Video video : iPages.getRecords()) {
                ossUtil.setAccessKeyId(global.getConfig().getAliyunId());
                ossUtil.setAccessKeySecret(global.getConfig().getAliyunKey());

                VideoResult videoResult = new VideoResult();
                videoResult.setId(video.getId());
                videoResult.setCreateAdmin(video.getCreateAdminName());
                videoResult.setCreateTime(Global.longToString(video.getCreateTime()));
                videoResult.setFilePath(ossUtil.getFileUrl(video.getFilePath(), 10000));
                videoResult.setCover(ossUtil.getVideoCover(video.getFilePath(), 10000));
                videoResult.setChatAdminName(video.getChatAdminName());
                videoResult.setType(video.getType());
                videoResult.setVideoType(video.getVideoType());
                videoResult.setVideoTypeName(video.getVideoTypeName());
                videoResult.setClickNum(video.getClickNum());
                videoResult.setLikeNum(video.getLikeNum());
                videoResult.setName(video.getName());
                videoResult.setIsTop(video.getIsTop());
                videoResult.setStatus(video.getStatus());
                videoResult.setStatusName(StatusEnums.getMessage(video.getStatus()));
                videoResult.setExpireTime(Global.longToString(video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L));
                if (video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L > System.currentTimeMillis()) {
                    videoResult.setIsExpire(2);
                } else {
                    videoResult.setIsExpire(1);
                }
                results.add(videoResult);
            }
            result.setData(results);
            result.setPage(page);
            result.setLimit(limit);
            result.setTotal(iPages.getTotal());
            msg = "获取成功";
            Resultstatus = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(Resultstatus);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Map<String, Object>> clickOrLike(Integer userId, String token, Integer videoId, int type) {
        if (type != 1) {
            ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "");
            if (apiResult.getStatus() != 1){
                return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);}
        }
        Video video = baseMapper.selectById(videoId);
        if (null != video) {
            long clickNum = video.getClickNum();
            long likeNum = video.getLikeNum();
            boolean isLiked = false;
            UserLike userLike = userLikeMapper.findByUserIdAndVideoId(userId, videoId);
            if (userLike != null) {
                isLiked = true;
            }
            switch (type) {
                case 1: // 点击
                    baseMapper.updateLikeOrCollect(videoId, type);
                    clickNum += 1;
                    ossUtil.setAccessKeyId(global.getConfig().getAliyunId());
                    ossUtil.setAccessKeySecret(global.getConfig().getAliyunKey());
                    video.setFilePath(ossUtil.getFileUrl(video.getFilePath(), 10000));
                    video.setCover(ossUtil.getVideoCover(video.getFilePath(), 10000));
                    break;
                case 2: // 点赞
                    if (!isLiked) {
                        userLike = new UserLike();
                        userLike.setUserId(userId);
                        userLike.setVideoId(videoId);
                        userLike.setStatus(1);
                        userLikeMapper.insert(userLike);
                        baseMapper.updateLikeOrCollect(videoId, 2);
                        likeNum += 1;
                        isLiked = true;
                    }
                    break;
                case 3: // 取消点赞
                    if (isLiked) {
                        userLikeMapper.deleteById(userLike.getId());
                        baseMapper.updateLikeOrCollect(videoId, 3);
                        likeNum -= 1;
                        isLiked = false;
                    }
                    break;
                default:
                    return new ApiResult<>(0, "无效的操作类型!", null);
            }
            // 创建返回对象
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("clickNum", clickNum);
            resultData.put("likeNum", likeNum);
            resultData.put("isLiked", isLiked);
            resultData.put("videoInfo", video);
            return new ApiResult<>(1, "操作成功", resultData);
        } else {
            return new ApiResult<>(0, "视频不存在!", null);
        }
    }

    public ListResult<List<VideoResult>> listVideoForA() {

        ListResult<List<VideoResult>> result = new ListResult<>();
        List<Video> list = list(Wrappers.<Video>lambdaQuery()
                .eq(Video::getIsTop, 1));
        int status = 0;
        String msg = "获取失败";
        try {
            if (CollectionUtils.isNotEmpty(list)) {
                List<VideoResult> results = new ArrayList<>();
                for (Video video : list) {
                    ossUtil.setAccessKeyId(global.getConfig().getAliyunId());
                    ossUtil.setAccessKeySecret(global.getConfig().getAliyunKey());

                    VideoResult videoResult = new VideoResult();
                    videoResult.setId(video.getId());
                    videoResult.setCreateAdmin(video.getCreateAdminName());
                    videoResult.setCreateTime(Global.longToString(video.getCreateTime()));
                    videoResult.setFilePath(ossUtil.getFileUrl(video.getFilePath(), 10000));
                    videoResult.setCover(ossUtil.getVideoCover(video.getFilePath(), 10000));
                    videoResult.setChatAdminName(video.getChatAdminName());
                    videoResult.setType(video.getType());
                    videoResult.setVideoType(video.getVideoType());
                    videoResult.setClickNum(video.getClickNum());
                    videoResult.setLikeNum(video.getLikeNum());
                    videoResult.setName(video.getName());
                    videoResult.setCover(video.getCover());
                    videoResult.setIsTop(video.getIsTop());
                    videoResult.setStatus(video.getStatus());
                    videoResult.setExpireTime(Global.longToString(video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L));
                    if (video.getCreateTime() + 30 * 24 * 60 * 60 * 1000L > System.currentTimeMillis()) {
                        videoResult.setIsExpire(2);
                    } else {
                        videoResult.setIsExpire(1);
                    }
                    results.add(videoResult);
                }
                result.setData(results);
                result.setTotal(list.size());
                msg = "获取成功";
                status = 1;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> auditVideo(Integer userId, String token, long videoId, int type) {

        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "");
        if (apiResult.getStatus() != 1){
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);}
        Video video = baseMapper.selectById(videoId);
        if (null != video) {
            ApiResult<Base> result = new ApiResult<>();
            int status = 1;
            String msg = "审核通过";
            video.setStatus(30);
            if (type == 0) {
                video.setStatus(25);
                msg = "审核未通过";
            } else if(type == 2){
                video.setStatus(40);
                msg = "视频已下架";
            } else if (type == 3){
                video.setIsTop(1);
                msg = "设置A区成功";
            } else if (type == 4){
                video.setIsTop(0);
                msg = "取消置为A区成功";
            }
            updateById(video);
            result.setStatus(status);
            result.setMsg(msg);
            return result;
        } else {
            return new ApiResult<>(0, "视频不存在!", null);
        }
    }
}
